package com.java.oauth.config;

import com.java.cg.user.feign.UserApi;
import com.java.oauth.util.UserJwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/*****
 * 自定义授权认证类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	ClientDetailsService clientDetailsService;

	@Autowired(required = false)
	private UserApi userApi;

	/****
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//=========================客户端信息认证start==================================
		//取出身份，如果身份为空说明没有认证
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		//没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
		if (authentication == null) {
			// 查询数据库
			ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
			if (clientDetails != null) {
				//秘钥
				String clientSecret = clientDetails.getClientSecret();
				//数据库查找方式
				return new User(username, clientSecret, AuthorityUtils.commaSeparatedStringToAuthorityList(""));
			}
		}
		//=========================客户端信息认证end==================================

		//=========================用户账号密码信息认证start==================================
		if (StringUtils.isEmpty(username)) {
			return null;
		}

		//根据用户名查询用户信息
//		String password = BCrypt.hashpw("123456", BCrypt.gensalt());
		// 通过数据库去查询用户通过密码授权
		com.java.cg.user.entity.User dbUser = userApi.findUserById(username);
		if (dbUser == null) {
			return null;
		}
		String password = dbUser.getPassword();
		//用户权限需要查询数据获取,这里写的假的作为演示数据
		String permissions = "ROLE_ADMIN,ROLE_USER"; //角色必须以ROLE_开头
		UserJwt userJwt = new UserJwt(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
		//=========================用户账号密码信息认证end==================================
		return userJwt;
	}
}
